package cn.hl.hm.controller.driver;

import cn.hl.hm.constants.DriverStatus;
import cn.hl.hm.constants.ModelConfig;
import cn.hl.hm.entity.Driver;
import cn.hl.hm.service.DriverService;
import cn.hl.hm.service.PushToAppIService;
import cn.hl.hm.service.SMSCodeIService;
import cn.hl.hm.util.BeanPicUtil;
import cn.hl.hm.util.FileUtil;
import cn.hl.hm.util.InfoCode;
import cn.hl.hm.util.OSSUtil;
import cn.hl.hm.util.QRCodeUtil;
import cn.hl.hm.util.Result;
import cn.hl.hm.util.json.GsonUtils;
import cn.hl.hm.util.token.TokenBean;
import cn.hl.hm.util.token.TokenUtil;
import com.vizhuo.smscode.model.SMSCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import static cn.hl.hm.util.MD5Util.MD5Encode;

/**
 * @author tarzan
 * @date 20171024 15:52
 */
@Controller
@RequestMapping("/driver/user/")
public class DriverUserController {
    private static final Logger logger = LoggerFactory.getLogger(DriverUserController.class);
    private final static SimpleDateFormat hhmmSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    SMSCodeIService sMSCodeIService;
    @Autowired
    DriverService driverService;
    @Autowired
    BeanPicUtil beanPicUtil;
    @Autowired
    PushToAppIService pushToAppIService;
    
    @Autowired
	private OSSUtil ossutil;

    /**
     * 司机登录
     *
     * @param driverAccount
     * @param password
     * @param appId
     * @param deviceToken
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@RequestParam String driverAccount, @RequestParam String password,
                        @RequestParam(required = false) String appId,
                        @RequestParam(required = false) String deviceToken,
                        HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("用户---登录---driver/login");
        request.setCharacterEncoding("UTF-8");
        Driver record = new Driver();
        record.setDriverAccount(driverAccount);
        record.setPassword(passwordEncode(password));
        try {
            List<Driver> selectDriver = driverService.selectDriver(record);
            if (null != selectDriver && selectDriver.size() > 0) {// 登录
                Driver result = selectDriver.get(0);
                // 登录
//                request.getSession().setAttribute("LOGIN_Driver_ACCOUNT", result.getDriverAccount());
//                request.getSession(false).setAttribute("Driver_SECURITY_TOKEN", result.getDeviceToken());
                // 司机登录活跃统计
                driverService.addHotRecord(result.getId(), "2", "1");
                // 更改操作时间
                Driver u = new Driver();
                u.setUpdateTime(new Date());
                u.setId(result.getId());
                if (StringUtils.isNoneBlank(deviceToken)) {
                    u.setDeviceToken(deviceToken);
                }
                driverService.updateDriver(u);
                result.setPassword(null);
                //新版不再返回旧版OurSecurityToken
                result.setOurSecurityToken(null);
                beanPicUtil.modifyUrl(result);
                addCookie(response, new TokenBean(result.getId(),result.getDriverAccount()));

                Result.ok(result, InfoCode.SUCCESS, response);
                return null;
            } else {
                Result.ok(null, InfoCode.AUTH_ERROR, response);
                return null;

            }
        } catch (Exception e) {
            Result.ok(null, InfoCode.FAILURE, response);
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 密码加密
     * @param password
     * @return
     */
    private String passwordEncode(String password){
        if(password!=null){
            return MD5Encode(MD5Encode(password, "utf-8"),"utf-8");
        }
        return null;
    }

    /**
     * 密码校验
     * @param password
     * @param md5Password
     * @return
     */
    private boolean passwordVerify(String password,String md5Password){
        if(password==null || password.length()==0){
            return false;
        }
        return passwordEncode(password).equals(md5Password);
    }

    public void addCookie(HttpServletResponse response, TokenBean tokenBean) {
        //新版token通过cookie返回给客户端
        String tokenKey= TokenUtil.getTokenKey(TokenUtil.PlatformEnum.DRIVER);
        String tokenValue= GsonUtils.toJson(tokenBean);
        TokenUtil.createToken(TokenUtil.PlatformEnum.DRIVER,tokenValue);
        Cookie cookie = new Cookie("driverToken", tokenKey);
        response.addCookie(cookie);
    }

    /**
     * @Title: checkMsg @Description: 忘记密码验证 验证码 @date: 2017年1月4日 @author:
     * 星矢 @param DriverAccount @param verifyCode @param
     * platformId @param request @param response @return @throws
     * IOException String @throws
     */
    @RequestMapping(value = "/checktMsgCode", method = RequestMethod.POST)
    public String checkMsg(@RequestParam String driverAccount, @RequestParam String verifyCode,
                           @RequestParam String appId, @RequestParam String type, // 1 找回密码
                           HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("用户---忘记密码验证---driver/checktMsgCode");
        request.setCharacterEncoding("UTF-8");
        Driver record = new Driver();
        record.setDriverAccount(driverAccount);
        try {
            if (type.equals("3")) {
                List<Driver> selectDriver = driverService.selectDriver(record);
                if (null != selectDriver && selectDriver.size() > 0) {
                    SMSCode sMSCode = new SMSCode();
                    sMSCode.setMobile(driverAccount);
                    sMSCode.setCode(verifyCode);
                    SMSCode smsCode = sMSCodeIService.findCode(sMSCode);
                    if (smsCode == null) {
                        Result.ok(null, InfoCode.MESSAGE_ERROR, response);
                        return null;
                    }
                    // 司机存在且验证码正确
                    Result.ok(null, InfoCode.SUCCESS, response);
                    return null;
                } else {
                    Result.ok(null, InfoCode.RESET_ERROR, response);
                    return null;

                }
            }
        } catch (Exception e) {
            Result.ok(null, InfoCode.FAILURE, response);
            return null;
        }
        return null;

    }

    /**
     * @Title: reset @Description: 忘记密码（重置） @date: 2017年1月4日 @author: 星矢 @param
     * DriverAccount @param password @param platformId @param
     * request @param response @return @throws IOException
     * String @throws
     */
    @RequestMapping(value = "/forget", method = RequestMethod.POST)
    public String reset(@RequestParam String driverAccount, @RequestParam String password, @RequestParam String appId,
                        HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("用户---忘记密码重置---driver/forget");
        request.setCharacterEncoding("UTF-8");
        Driver record = new Driver();
        record.setDriverAccount(driverAccount);
        try {
            List<Driver> selectDriver = driverService.selectDriver(record);
            if (null != selectDriver && selectDriver.size() > 0) {// 登录
                Driver result = selectDriver.get(0);
                result.setUpdateTime(new Date());
                result.setPassword(passwordEncode(password));
                if (StringUtils.isNotBlank(appId)) {
                    result.setPlatformId(appId);
                }
                int updateDriver = driverService.updateDriver(result);
                if (updateDriver > 0) {
                    Result.ok(result, InfoCode.SUCCESS, response);
                    return null;
                } else {
                    Result.ok(null, InfoCode.FAILURE, response);
                    return null;
                }
            } else {
                Result.ok(null, InfoCode.RESET_ERROR, response);
                return null;

            }
        } catch (Exception e) {
            Result.ok(null, InfoCode.FAILURE, response);
            return null;
        }

    }

    /**
     * @Title: loginout @Description: 退出 @date: 2017年1月4日 @author: 星矢 @param
     * DriverAccount @param platformId @param request @param
     * response @return @throws IOException String @throws
     */
    @RequestMapping(value = "/loginout", method = RequestMethod.POST)
    public String loginout(
            @CookieValue(required = false,value = "driverToken") String driverToken,
            @RequestParam String driverAccount, @RequestParam String appId, HttpServletRequest request,
                           HttpServletResponse response) throws IOException {
        logger.info("用户---退出登录---driver/loginout");
        request.setCharacterEncoding("UTF-8");
        Driver record = new Driver();
        record.setDriverAccount(driverAccount);
        try {
//            request.getSession().removeAttribute("LOGIN_DRIVER_ACCOUNT");
//            request.getSession(false).removeAttribute("DRIVER_SECURITY_TOKEN");
            TokenUtil.cleanToken(driverToken);
            Result.ok(null, InfoCode.SUCCESS, response);
            return null;
        } catch (Exception e) {
            Result.ok(null, InfoCode.FAILURE, response);
            return null;
        }
    }

    /**
     * @Title: updatePass @Description: 修改密码 @date: 2017年1月4日 @author: 星矢 @param
     * DriverAccount @param oldPass @param newPass @param
     * platformId @param request @param response @return @throws
     * IOException String @throws
     */
    @RequestMapping(value = "/updatePass", method = RequestMethod.POST)
    public String updatePass(@RequestParam String driverAccount, @RequestParam String oldPass,
                             @RequestParam String newPass, @RequestParam String appId, HttpServletRequest request,
                             HttpServletResponse response) throws IOException {
        logger.info("用户---司机修改登录密码---driver/updatePass");
        request.setCharacterEncoding("UTF-8");
        Driver record = new Driver();
        record.setDriverAccount(driverAccount);
        record.setPassword(passwordEncode(oldPass));

        try {
            List<Driver> selectDriver = driverService.selectDriver(record);
            if (null != selectDriver && selectDriver.size() > 0) {
                Driver result = selectDriver.get(0);
                result.setUpdateTime(new Date());
                result.setPassword(passwordEncode(newPass));
                if (StringUtils.isNotBlank(appId)) {
                    result.setPlatformId(appId);
                }
                int updateDriver = driverService.updateDriver(result);
                if (updateDriver > 0) {
                    Result.ok(result, InfoCode.SUCCESS, response);
                    return null;
                } else {
                    Result.ok(null, InfoCode.FAILURE, response);
                    return null;
                }
            } else {
                Result.ok(null, InfoCode.AUTH_ERROR, response);
                return null;

            }
        } catch (Exception e) {
            Result.ok(null, InfoCode.FAILURE, response);
            return null;
        }

    }

    /**
     * @Title: regist @Description: 注册 @date: 2017年1月4日 @author: 星矢 @param
     * DriverAccount @param verifyCode @param platformId @param
     * password @param invitationCode @param request @param
     * response @return @throws IOException String @throws
     */
    @RequestMapping(value = "/regist", method = RequestMethod.POST)
    public String regist(@RequestParam String driverAccount, @RequestParam String verifyCode, String appId,
                         @RequestParam String password, String deviceToken, // 推送
                         String invitationCode, // 邀请码 预留
                         HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("用户---注册---driver/regist");
        request.setCharacterEncoding("UTF-8");
        if (StringUtils.isNotBlank(invitationCode)) {
            // 预留功能
        }
        // 1 验证码
        // SMSCode sMSCode = new SMSCode();
        // sMSCode.setMobile(driverAccount);
        // sMSCode.setCode(verifyCode);
        try {
            // SMSCode smsCode = sMSCodeIService.findCode(sMSCode);
            // if (smsCode == null) {
            // Result.ok(null, InfoCode.MESSAGE_ERROR, response);
            // return null;
            // }
            // 是否重复注册
            Driver param = new Driver();
            param.setDriverAccount(driverAccount);
            List<Driver> selectDriver = driverService.selectDriver(param);
            if (selectDriver != null && selectDriver.size() > 0) {
                Result.ok(null, InfoCode.REGIST_ERROR, response);
                return null;
            }

            Driver record = new Driver();
            if (StringUtils.isNotBlank(appId)) {
                record.setPlatformId(appId);
            }
            record.setPassword(passwordEncode(password));
            record.setDriverPhone(driverAccount);
            record.setDriverAccount(driverAccount);
//            record.setOurSecurityToken(TokenProcessor.getInstance().generateToken());
            if (StringUtils.isNoneBlank(deviceToken)) {
                record.setDeviceToken(deviceToken);
            }
            record.setDriverStatus(DriverStatus.WAIT_SUBMIT.getStatus());
            record.setCreateTime(new Date());
            record.setUpdateTime(new Date());

            // 二维码
            String preUrl = ModelConfig.ENV_TEST;
            String rebackUrl = ModelConfig.QR_PIC_DRIVER_LONG_TEST;

            if (ModelConfig.status.equals("1")) {
                preUrl = ModelConfig.ENV_ONLINE;
                rebackUrl = ModelConfig.QR_PIC_DRIVER_LONG_ONLINE;
            }
            String content = preUrl + "driver/selectInfoByget?driverAccount=" + driverAccount;
            String destPath = ModelConfig.QR_PIC_DRIVER_SHORT;

            String finalPicUrl = QRCodeUtil.encodeDriverOrPay(content, destPath, false);
//            StringBuffer sb = new StringBuffer();
//            // 回显路径
//            String str = sb.append(rebackUrl).append(finalPicUrl).toString();
            File file =new File(destPath+finalPicUrl);
            if(file.exists()) {
            	ossutil.putObject("hm/qrInfo/"+finalPicUrl, file);
            // TODO 入库 并返回客户端
            record.setQrInfo("hm/qrInfo/"+finalPicUrl);
            FileUtil.delFile(destPath+finalPicUrl);
            }
            int add = driverService.addDriver(record);
            if (add > 0) {
                // 司机注册活跃统计
//                request.getSession().setAttribute("LOGIN_Driver_ACCOUNT", record.getDriverAccount());
//                request.getSession(false).setAttribute("Driver_SECURITY_TOKEN", record.getDeviceToken());
                driverService.addHotRecord(record.getId(), "2", "2");
                record.setPassword(null);
                record.setOurSecurityToken(null);
                addCookie(response, new TokenBean(record.getId(),record.getDriverAccount()));
                Result.ok(record, InfoCode.SUCCESS, response);
            } else {
                addCookie(response, new TokenBean(record.getId(),record.getDriverAccount()));
                Result.ok(null, InfoCode.SUCCESS, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Result.ok(null, InfoCode.FAILURE, response);
        }
        return null;
    }

//    /**
//     * @Title: regist @Description: 注册 @date: 2017年1月4日 @author: 星矢 @param
//     * DriverAccount @param verifyCode @param platformId @param
//     * password @param invitationCode @param request @param
//     * response @return @throws IOException String @throws
//     */
//    @RequestMapping(value = "/addDriver", method = RequestMethod.POST)
//    public String addDriver(Driver driver, @RequestParam String appId, HttpServletRequest request,
//                            HttpServletResponse response) throws IOException {
//        logger.info("司机管理---添加司机---driver/addDriver");
//        request.setCharacterEncoding("UTF-8");
//        try {
//            Driver param = new Driver();
//            if (StringUtils.isNotBlank(appId)) {
//                driver.setPlatformId(appId);
//            }
//            // 是否重复注册
//            param.setDriverAccount(driver.getDriverPhone());
//            List<Driver> selectDriver = driverService.selectDriver(param);
//            if (selectDriver != null && selectDriver.size() > 0) {
//                Result.ok(null, InfoCode.REGIST_ERROR, response);
//                return null;
//            }
//            driver = beanPicUtil.cutUrl(driver);
//
//            String pass = NumberUtils.getRandomNumber(6);
//            driver.setDriverAccount(driver.getDriverPhone());
//            driver.setPassword(MD5Util.MD5Encode(MD5Util.MD5Encode(pass, "UTF-8"), "UTF-8"));
//            driver.setOurSecurityToken(TokenProcessor.getInstance().generateToken());
//            driver.setOurSecurityToken(TokenProcessor.getInstance().generateToken());
//            driver.setDriverStatus(DriverStatus.PASS.getStatus());
//            driver.setCreateTime(new Date());
//            driver.setUpdateTime(new Date());
//            driver.setWorkStatus("1");
//
//            // 二维码
//            String preUrl = ModelConfig.ENV_TEST;
//            String rebackUrl = ModelConfig.QR_PIC_DRIVER_LONG_TEST;
//
//            if (ModelConfig.status.equals("1")) {
//                preUrl = ModelConfig.ENV_ONLINE;
//                rebackUrl = ModelConfig.QR_PIC_DRIVER_LONG_ONLINE;
//
//            }
//            String content = preUrl + "driver/selectInfoByget?driverAccount=" + driver.getDriverAccount();
//            String destPath = ModelConfig.QR_PIC_DRIVER_SHORT;
//
//            String finalPicUrl = QRCodeUtil.encodeDriverOrPay(content, destPath, false);
//            StringBuffer sb = new StringBuffer();
//            // 回显路径
//            String str = sb.append(rebackUrl).append(finalPicUrl).toString();
//            // TODO 入库 并返回客户端
//            driver.setQrInfo(str);
//
//            if (driver.getVehicleTypeId() != null && driver.getVlId() != null) {
//                VtVl vv = new VtVl();
//                vv.setVehicleTypeId(Integer.parseInt(driver.getVehicleTypeId()));
//                vv.setVehicleLengthId(Integer.parseInt(driver.getVlId()));
//                List<VtVl> l = vtVlMapper.selectVtVlList(vv);
//
//                if (l != null && l.size() > 0) {
//                    driver.setVtVlId(l.get(0).getId().toString());
//                } else {
//                    // 如果不存在，则执行插入，同时向路线-车辆-价格表中新增数据（所有路线均可 包含该车型）
//                    VtVl v = new VtVl();
//                    if (driver.getVehicleTypeId() != null) {
//                        v.setVehicleTypeId(Integer.parseInt(driver.getVehicleTypeId()));
//                    }
//                    v.setVehicleLengthId(Integer.parseInt(driver.getVlId()));
//                    v.setCreateTime(new Date().toLocaleString());
//                    int i = vtVlMapper.insertSelective(v);
//                    if (i > 0) {
//                        driver.setVtVlId(v.getId().toString());
//                    }
//                    // 获取车型
//                    VehicleType vt = new VehicleType();
//                    vt.setStatus("0");
//                    Route r = new Route();
//                    r.setRouteStatus("0");
//                    List<Route> route = routeService.selectRoute(null);
//                    // 增加一个车型，则所有路线都增加该车型double
//                    for (Route route2 : route) {
//                        RouteVehiclePrice rvp = new RouteVehiclePrice();
//                        rvp.setPrice(new BigDecimal(0));
//                        rvp.setRouteId(route2.getId());
//                        rvp.setDateTime(new Date().toLocaleString());
//                        rvp.setVtVlId(Integer.parseInt(driver.getVtVlId()));
//                        rvpService.addRouteVehiclePrice(rvp);
//                    }
//
//                }
//            }
//            int add = driverService.addDriver(driver);
//            if (add > 0) {
//                // 发短信
//                // TestSDKClient.testSendSMSE(driver.getDriverAccount(), "【华凌】"
//                // + "恭喜您注册成功 ： 用户名 "+record.getDriverAccount()+" 密码
//                // "+pass+"，请勿向他人泄露。");
//                Result.ok(driver, InfoCode.SUCCESS, response);
//                // Result.ok(record, InfoCode.SUCCESS, response);
//            } else {
//                Result.ok(null, InfoCode.FAILURE, response);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            Result.ok(null, InfoCode.FAILURE, response);
//        }
//        return null;
//    }

    /**
     * @Title: updateInfo @Description: 更新司机信息 @date: 2017年1月4日 @author:
     * 星矢 @param DriverAccount @param platformId @param Driver @param
     * request @param response @return @throws IOException
     * String @throws
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String updateInfo(
            @CookieValue(required = false,value = "driverToken") String driverToken,
            String appId,Driver driver, String type, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        {
            logger.info("个人中心/司机管理---更新司机信息/修改司机---driver/user/update");
            request.setCharacterEncoding("UTF-8");
            if (driver == null) {
                Result.ok(null, InfoCode.PARAM_ERROR, response);
                return null;
            }
            try {
                if(type!=null&&!type.equals("")) {
                    if(type.equals("2")) {
                        if(driver.getFreeDay()!=null  && driver.getFreeDay().intValue()!=0 ){
                            Calendar freeTime = new GregorianCalendar();
                            freeTime.setTime(new Date());
                            freeTime.add(Calendar.DAY_OF_MONTH, driver.getFreeDay().intValue()-1);
                            freeTime.set(Calendar.HOUR_OF_DAY, 23);
                            freeTime.set(Calendar.MINUTE, 59);
                            freeTime.set(Calendar.SECOND, 59);
                            driver.setFreeTime(freeTime.getTime());
                            driver.setIsSecurity("0");
                        }
                    }else if(type.equals("0")){
                        if(driver.getIsSecurity()!=null&&driver.getIsSecurity().equals("0")) {
                            if(driver.getFreeDay()==null || driver.getFreeDay().intValue()==0) {
                                driver.setFreeTime(null);
                                driver.setFreeDayFlag(1);
                            }
                        }
                    }
                }
                driver = beanPicUtil.cutUrl(driver);
                Driver result = driverService.selectByPrimaryKey(TokenUtil.getTokenBean(driverToken).getId());
                if (result != null) {
                    driver.setId(result.getId());
                    driver.setUpdateTime(new Date());
                    if (result.getQrInfo() != null && !"".equals(result.getQrInfo())) {
                        driver.setQrInfo(result.getQrInfo());
                    }
                    if (StringUtils.isNotBlank(appId)) {
                        driver.setPlatformId(appId);
                    }
                    if (driver.getQrInfo() == null) {
                        // 二维码
                        String preUrl = ModelConfig.ENV_TEST;
                        String rebackUrl = ModelConfig.QR_PIC_DRIVER_LONG_TEST;

                        if (ModelConfig.status.equals("1")) {
                            preUrl = ModelConfig.ENV_ONLINE;
                            rebackUrl = ModelConfig.QR_PIC_DRIVER_LONG_ONLINE;

                        }
                        String content = preUrl + "driverController/selectInfoByget?driverAccount=" + result.getDriverAccount();
                        String destPath = ModelConfig.QR_PIC_DRIVER_SHORT;

                        String finalPicUrl = QRCodeUtil.encodeDriverOrPay(content, destPath, false);
                        StringBuffer sb = new StringBuffer();
                        // 回显路径
                        String str = sb.append(rebackUrl).append(finalPicUrl).toString();
                        // TODO 入库 并返回客户端
                        File file =new File(destPath+finalPicUrl);
                        if(file.exists()) {
                        	ossutil.putObject("hm/qrInfo/"+finalPicUrl, file);
                        // TODO 入库 并返回客户端
                        driver.setQrInfo("hm/qrInfo/"+finalPicUrl);
                        FileUtil.delFile(destPath+finalPicUrl);
                        }
                    }
                    driver.setDriverStatus(DriverStatus.WAIT_AUDIT.getStatus());
                    driverService.updateDriver(driver);
                    Result.ok(null, InfoCode.SUCCESS, response);
                    return null;
                } else {
                    Result.ok(null, InfoCode.PARAM_ERROR, response);
                    return null;
                }

            } catch (Exception e) {
                e.printStackTrace();
                Result.ok(null, InfoCode.FAILURE, response);
            }
            return null;
        }
    }
//
//    /**
//     * @Title: updateInfo @Description: 更新司机信息 @date: 2017年1月4日 @author:
//     * 星矢 @param DriverAccount @param platformId @param Driver @param
//     * request @param response @return @throws IOException
//     * String @throws
//     */
//    @RequestMapping(value = "/auditDriverInfo", method = RequestMethod.POST)
//    public String auditDriverInfo(@RequestParam String driverAccount, @RequestParam String appId, Driver driver,
//                                  @RequestParam String driverStatus, HttpServletRequest request, HttpServletResponse response)
//            throws IOException {
//        request.setCharacterEncoding("UTF-8");
//        if (driver == null) {
//            Result.ok(null, InfoCode.PARAM_ERROR, response);
//            return null;
//        }
//        if (driverStatus.equals(DriverStatus.FAIL.getStatus()) && StringUtils.isBlank(driver.getDriverUnpassReason())) {
//            Result.ok(null, InfoCode.PARAM_ERROR, response);
//            return null;
//        }
//        try {
//            Driver param = new Driver();
//            param.setDriverAccount(driverAccount);
//            driver = beanPicUtil.cutUrl(driver);
//            List<Driver> selectDriver = driverService.selectDriver(param);
//            if (selectDriver != null && selectDriver.size() > 0) {
//                Driver result = selectDriver.get(0);
//                driver.setId(result.getId());
//                driver.setUpdateTime(new Date());
//                // driver.setDriverStatus(DriverStatus.WAIT_AUDIT.getStatus());
//                if (StringUtils.isNotBlank(appId)) {
//                    driver.setPlatformId(appId);
//                }
//
//                // 二维码
//                String preUrl = ModelConfig.ENV_TEST;
//                String rebackUrl = ModelConfig.QR_PIC_DRIVER_LONG_TEST;
//
//                if (ModelConfig.status.equals("1")) {
//                    preUrl = ModelConfig.ENV_ONLINE;
//                    rebackUrl = ModelConfig.QR_PIC_DRIVER_LONG_ONLINE;
//
//                }
//                String content = preUrl + "driver/selectInfoByget?driverAccount=" + driverAccount;
//                String destPath = ModelConfig.QR_PIC_DRIVER_SHORT;
//
//                String finalPicUrl = QRCodeUtil.encodeDriverOrPay(content, destPath, false);
//                StringBuffer sb = new StringBuffer();
//                // 回显路径
//                String str = sb.append(rebackUrl).append(finalPicUrl).toString();
//                // TODO 入库 并返回客户端
//                driver.setQrInfo(str);
//                int update = driverService.updateDriver(driver);
//                if (update > 0) {
//                    if (driverStatus.equals(DriverStatus.PASS.getStatus())) {
//                        Driver userParam3 = new Driver();
//                        userParam3.setDriverAccount(driverAccount);
//                        List<Driver> selectdriver2 = driverService.selectDriver(userParam3);
//                        if (selectdriver2 != null && selectdriver2.size() > 0) {
//                            Driver driver2 = selectdriver2.get(0);
//
//                            if (StringUtils.isNotBlank(driver2.getDeviceToken())) {
//                                Push push = new Push();
//                                push.setPtype(3);
//                                push.setPushoid("");
//                                push.setContext("恭喜您，资料已审核成功，马上开始接单吧");// 要发送的内容
//                                push.setDisplayType("notification");// message:
//                                // 消息，通知：notification
//                                push.setOperationType(1);// 用户类型：1司机，2发货端
//                                push.setPushClient("driverPushClient");// 使用的推送Client
//                                push.setPushType("listcast");// unicast：单播 //
//                                // listcast：列表
//                                push.setTitle("资料审核通过"); // 发送的标题
//                                push.setTokenStr(new String[]{driver2.getDeviceToken()}); // 要发送手机的token
//                                // ios & android推送公共调用方法
//                                pushToAppIService.pushCommon(push);
//                            }
//                        }
//                    }
//                }
//                Result.ok(null, InfoCode.SUCCESS, response);
//
//                return null;
//            } else {
//                Result.ok(null, InfoCode.PARAM_ERROR, response);
//                return null;
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            Result.ok(null, InfoCode.FAILURE, response);
//        }
//        return null;
//    }

//    @RequestMapping(value = "/selectInfo", method = RequestMethod.POST)
//    public String selectInfo(@RequestParam String driverAccount, HttpServletRequest request,
//                             HttpServletResponse response) throws IOException {
//        logger.info("个人中心/司机管理---司机详情/司机详情---driver/selectInfo");
//        request.setCharacterEncoding("UTF-8");
//        try {
//            Driver param = new Driver();
//            param.setDriverAccount(driverAccount);
//            List<Driver> selectDrivercheck = driverService.selectDriver(param);
//            if (selectDrivercheck != null && selectDrivercheck.size() > 0) {
//                Driver d = selectDrivercheck.get(0);
//                d.setPassword(null);
//                if (d.getVehicleTypeId() != null) {
//                    param.setDriverStatus(d.getDriverStatus());
//                }
//            } else {
//                Result.ok(null, InfoCode.SUCCESS, response);
//            }
//            List<Driver> selectDriver = driverService.selectDriverInfo(param);
//            if (selectDriver != null && selectDriver.size() > 0) {
//                //可用余额
//                selectDriver.get(0).setUsableCash(selectDriver.get(0).getRemainCash().subtract(selectDriver.get(0).getWithdrawCash()));
//                Driver modifyUrl = beanPicUtil.modifyUrl(selectDriver.get(0));
//                Result.ok(modifyUrl, InfoCode.SUCCESS, response);
//            } else {
//                Result.ok(null, InfoCode.SUCCESS, response);
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            Result.ok(null, InfoCode.SUCCESS, response);
//        }
//        return null;
//    }

//    @RequestMapping(value = "/selectInfoByget", method = RequestMethod.GET)
//    public String selectInfoByget(@RequestParam String driverAccount, String qrFlag, Integer channel, // 渠道，默认干线渠道为1
//                                  // 线下为2
//                                  // ，不传为1
//                                  HttpServletRequest request, HttpServletResponse response) throws IOException {
//        logger.info("订单---获取通行证信息---driver/selectInfoByget");
//        request.setCharacterEncoding("UTF-8");
//        try {
//            Driver param = new Driver();
//            param.setDriverAccount(driverAccount);
//            List<Driver> selectDrivercheck = driverService.selectDriver(param);
//            if (selectDrivercheck != null && selectDrivercheck.size() > 0) {
//                Driver d = selectDrivercheck.get(0);
//                if (d.getVehicleTypeId() != null) {
//                    param.setDriverStatus(d.getDriverStatus());
//                }
//            } else {
//                Result.ok(null, InfoCode.SUCCESS, response);
//            }
//            List<Driver> selectDriver = driverService.selectDriverInfo(param);
//            // TODO
//            if (channel == null) {
//                channel = 1;
//            }
//            ChannelDiscount selectByPrimaryKey = channelDiscountMapper.selectByPrimaryKey(channel);
//            if (selectDriver != null && selectDriver.size() > 0) {
//                Driver t = selectDriver.get(0);
//                t.setPassword(null);
//                if (t.getQrFlag() == null && qrFlag == null) {
//
//                } else if (t.getQrFlag() != null && qrFlag == null) {
//                    Result.ok(null, InfoCode.SUCCESS, response);
//                    return null;
//                } else if (t.getQrFlag() != null && "".equals(qrFlag)) {
//                    Result.ok(null, InfoCode.SUCCESS, response);
//                    return null;
//                } else if (t.getQrFlag() == null && "".equals(qrFlag)) {
//                } else {
//                    if (qrFlag != null && !qrFlag.equals("")) {
//                        if (!qrFlag.equals(t.getQrFlag())) {
//                            Result.ok(null, InfoCode.SUCCESS, response);
//                            return null;
//                        }
//                    }
//                }
//                Driver modifyUrl = beanPicUtil.modifyUrl(t);
//                modifyUrl.setUsableCash(modifyUrl.getRemainCash().subtract(modifyUrl.getWithdrawCash()));
//                modifyUrl.setChannelDiscount(selectByPrimaryKey);
//                Result.ok(modifyUrl, InfoCode.SUCCESS, response);
//            } else {
//                Result.ok(null, InfoCode.SUCCESS, response);
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            Result.ok(null, InfoCode.SUCCESS, response);
//        }
//        return null;
//    }
//
//    @RequestMapping(value = "/updateDeviceToken", method = RequestMethod.POST)
//    public String updateDeviceToken(@RequestParam String driverAccount, @RequestParam String deviceToken, // 推送
//                                    String appId, HttpServletRequest request, HttpServletResponse response) throws IOException {
//        try {
//            request.setCharacterEncoding("UTF-8");
//            Driver param = new Driver();
//            param.setDriverAccount(driverAccount);
//            List<Driver> selectUser = driverService.selectDriver(param);
//            if (selectUser == null) {
//                Result.ok(null, InfoCode.PARAM_ERROR, response);
//                return null;
//            }
//
//            Driver record = new Driver();
//            if (StringUtils.isNotBlank(appId)) {
//                record.setPlatformId(appId);
//            }
//            record.setDriverAccount(driverAccount);
//            if (StringUtils.isNoneBlank(deviceToken)) {
//                record.setDeviceToken(deviceToken);
//            }
//            record.setId(selectUser.get(0).getId());
//            record.setUpdateTime(new Date());
//            int add = driverService.updateDriver(record);
//            if (add > 0) {
//                Result.ok(null, InfoCode.SUCCESS, response);
//            } else {
//                Result.ok(null, InfoCode.FAILURE, response);
//
//            }
//        } catch (Exception e) {
//            Result.ok(null, InfoCode.FAILURE, response);
//        }
//        return null;
//    }
//
//    /**
//     * 当前进行中的订单 1：当前订单列表 2：订单收入列表，3历史订单列表 4 所有订单列表
//     *
//     * @param driverId
//     * @param pageId
//     * @param pageCount
//     * @param request
//     * @param response
//     * @return
//     * @throws IOException
//     */
//    @RequestMapping(value = "/selectOrderList", method = RequestMethod.POST)
//    public String selectOrderList(@RequestParam Integer type, @RequestParam Integer driverId,
//                                  @RequestParam Integer pageId, @RequestParam Integer pageCount, HttpServletRequest request,
//                                  HttpServletResponse response) throws IOException {
//        logger.info("订单业务---获取当前订单列表/订单收入列表---driver/selectOrderList");
//        request.setCharacterEncoding("UTF-8");
//        try {
//            AppPager handle = AppPager.handle(pageId, pageCount);
//            Order param = new Order();
//            param.setPageId(handle.getPageId());
//            param.setPageCount(handle.getPageCount());
//
//			/*
//             * orderstatus1：待接单 2：待付款（已接单） 3：待送达（已付款） 4：待点评 5：待打款（线下给司机打款）
//			 * 6：已完成（已打款） 20：关闭（取消/关闭）
//			 */
//            Map map = new HashMap<>();
//            OrderVO o = driverService.selectOrderOtherInfo(driverId);
//            if (type == 1) {
//                param.setDriverId(driverId);
//                param.setOrderStatus("13"); // orderStatus 2.3.4
//            } else if (type == 2) {
//                param.setDriverId(driverId);
//                param.setOrderStatus("14"); // orderStatus 5,6
//            } else if (type == 3) {
//                param.setDriverId(driverId);
//            } else if (type == 4) {
//                param.setDriverId(driverId);
//            } else {
//                param.setDriverId(driverId);
//                param.setOrderStatus("6"); // 已打款订单
//            }
//            map.put("totalIncome", o.getTotalIncome());
//            map.put("totalOrderCount", o.getTotalOrderCount());
//            map.put("successOrderCount", o.getSuccessOrderCount());
//            map.put("favourableCommentPercent", o.getFavourableCommentPercent());
//            List<Order> orderList = orderService.selectOrder(param);
//            map.put("orderList", orderList);
//            Result.ok(map, InfoCode.SUCCESS, response);
//        } catch (Exception e) {
//            e.printStackTrace();
//            Result.ok(null, InfoCode.FAILURE, response);
//        }
//        return null;
//    }
//
//    /**
//     * 司机点击确认送达
//     * @param orderCode
//     * @param request
//     * @param response
//     * @return
//     * @throws IOException
//     */
//    @RequestMapping(value = "/driverConfirmOrder", method = RequestMethod.POST)
//    public String driverConfirmOrder(@RequestParam String orderCode, HttpServletRequest request,
//                                     HttpServletResponse response) throws IOException {
//        logger.info("订单业务---司机确认送达---driver/driverConfirmOrder");
//        request.setCharacterEncoding("UTF-8");
//        try {
//            Order orderParam = new Order();
//            orderParam.setOrderCode(orderCode);
//            List<Order> selectOrder = orderService.selectOrder(orderParam);
//            if (selectOrder != null && selectOrder.size() > 0) {
//                Order order = selectOrder.get(0);
//                String orderStatus = order.getOrderStatus();
//                if (orderStatus.equals(OrderStatus.TO_ARRIVE.getStatus())
//                        || orderStatus.equals(OrderStatus.TO_COMMENT.getStatus())) {
//                    order.setDriverEnsureStatus("2");
//                    order.setDriverEnsureTime(new Date());
//                    int updateOrderById = orderService.updateOrderById(order);
//                    if (updateOrderById > 0) {
//
//                        User user = new User();
//                        user.setUserAccount(order.getUserAccount());
//                        List<User> selectUser = userService.selectUser(user);
//
//                        if (selectUser != null && selectUser.size() > 0) {
//                            User user2 = selectUser.get(0);
//                            // push
//                            if (StringUtils.isNotBlank(user2.getUserAccount())
//                                    && StringUtils.isNotBlank(user2.getDeviceToken())) {
//                                Push push = new Push();
//                                push.setPtype(1);
//                                push.setPushoid(order.getOrderCode());
//                                push.setContext("您的货物已妥善送达，请尽快确认收货。");// 要发送的内容
//                                push.setDisplayType("notification");// message:
//                                // 消息，通知：notification
//                                push.setOperationType(2);// 用户类型：1司机，2发货端
//                                push.setPushClient("consignerPushClient");// 使用的推送Client
//                                // 是往发货端：consignerPushClient
//                                // 或
//                                // 司机端发送：driverPushClient。
//                                push.setPushType("listcast");// unicast：单播
//                                // //
//                                // listcast：列表
//                                push.setTitle("货物送达"); // 发送的标题
//                                push.setTokenStr(new String[]{user2.getDeviceToken()}); // 要发送手机的token
//                                // ios & android推送公共调用方法
//                                pushToAppIService.pushCommon(push);
//                            }
//                        }
//                    } else {
//                        Result.ok(null, InfoCode.FAILURE, response);
//                        return null;
//                    }
//                    Result.ok(null, InfoCode.SUCCESS, response);
//                    return null;
//                }
//            }
//        } catch (Exception e) {
//            Result.ok(null, InfoCode.FAILURE, response);
//        }
//        Result.ok(null, InfoCode.SUCCESS, response);
//        return null;
//    }
//
//    // 上报司机坐标
//    @RequestMapping(value = "/uploadLocation", method = RequestMethod.POST)
//    public String uploadLocation(@RequestParam Double lat, @RequestParam Double lng,
//                                 @RequestParam(value = "driverId", required = false) Integer driverId, HttpServletRequest request,
//                                 HttpServletResponse response) {
//        logger.info("司机经纬度---上传司机经纬度---driver/uploadLocation");
//        if (null == lat || null == lng || "null".equals(lat) || "null".equals(lng)) {
//            Result.ok(null, InfoCode.FAILURE, response);
//            return null;
//        }
//        int i = 0;
//        DriverLatitudeLongitude dll = new DriverLatitudeLongitude();
//        dll.setLat(lat);
//        dll.setLng(lng);
//
//        if (driverId != null && !("null".equals(driverId))) {
//            dll.setDriverId(driverId);
//            ;
//        }
//        i = dllService.operDriverLatitudeLongitude(dll);
//        if (i > 0) {
//            Result.ok(null, InfoCode.SUCCESS, response);
//            return null;
//        } else {
//            Result.ok(null, InfoCode.FAILURE, response);
//        }
//        return null;
//    }
//
//    // 上报司机坐标
//    @RequestMapping(value = "/getDriverLocation", method = RequestMethod.POST)
//    public String getDriverLocation(@RequestParam(value = "driverId", required = true) Integer driverId,
//                                    HttpServletRequest request, HttpServletResponse response) {
//        logger.info("司机经纬度---获取司机经纬度---driver/getDriverLocation");
//        if (null == driverId || "null".equals(driverId)) {
//            Result.ok(null, InfoCode.FAILURE, response);
//            return null;
//        }
//        int i = 0;
//        DriverLatitudeLongitude dll = new DriverLatitudeLongitude();
//        dll.setDriverId(driverId);
//        ;
//        List<DriverLatitudeLongitude> ddlList = dllService.selectDriverLatitudeLongitude(dll);
//        if (ddlList != null && ddlList.size() > 0) {
//            Result.ok(ddlList.get(0), InfoCode.SUCCESS, response);
//            return null;
//        } else {
//            Result.ok(null, InfoCode.SUCCESS, response);
//        }
//        return null;
//    }
//
//    // 获取司机经纬度信息
//    @RequestMapping(value = "/getAllDriverLocation", method = RequestMethod.POST)
//    public String getAllDriverLocation(@RequestParam(value = "driverId", required = false) Integer driverId,
//                                       HttpServletRequest request, HttpServletResponse response) {
//        logger.info("司机经纬度---所有司机经纬度信息---driver/getAllDriverLocation");
//        // if(null == driverId || "null".equals(driverId)){
//        // Result.ok(null, InfoCode.FAILURE, response);
//        // return null;
//        // }
//        int i = 0;
//        // DriverLatitudeLongitude dll = new DriverLatitudeLongitude();
//        // dll.setDriverId(driverId);;
//        List<DriverLatitudeLongitude> ddlList = dllService.selectDriverLatitudeLongitude(null);
//        DriverLatitudeLongitudeVO lVo = new DriverLatitudeLongitudeVO();
//        if (ddlList != null && ddlList.size() > 0) {
//            List driverList = driverService.selectDriver(null); // 司机总数量==车辆总数量
//            Order order = new Order();
//            order.setOrderStatus("13"); // 进行中
//            List orderList = new ArrayList<>();
//            orderList = orderService.selectOrder(order);
//            if (driverList != null && driverList.size() > 0) {
//                lVo.setBusyCount(orderList.size());
//                lVo.setFreeCount(driverList.size() - orderList.size());
//            }
//            lVo.setLlList(ddlList);
//            Result.ok(lVo, InfoCode.SUCCESS, response);
//            return null;
//        } else {
//            Result.ok(null, InfoCode.SUCCESS, response);
//        }
//        return null;
//    }
//
//    /********************************************************
//     * ******** ******** 后台功能 ******** ******** ******** ********
//     ******************************************************/
//    /*
//	 * 1. 待提交 2. 待审核 3. 已通过 4. 未通过 5. 无效
//	 */
//    @RequestMapping(value = "/backSelectDriverList", method = RequestMethod.POST)
//    public String backSelectDriverList(Driver driver, @RequestParam Integer pageId, @RequestParam Integer pageCount,
//                                       HttpServletRequest request, HttpServletResponse response) {
//        logger.info("司机管理---司机列表---driver/backSelectDriverList");
//        try {
//            AppPager handle = AppPager.handle(pageId, pageCount);
//
//            driver.setPageId(handle.getPageId());
//            driver.setPageCount(handle.getPageCount());
//
//            List<Driver> ddlList = driverService.selectDriverInfo(driver);
//            driver.setPageCount(null);
//            driver.setPageId(null);
//            List<Driver> list = driverService.selectDriverInfo(driver);
////			driver.setPageCount(null);
////			driver.setPageId(null);
////			int selectDriverCount = driverMapper.selectDriverCount(driver);
//
//            Map<String, Object> pageInfo = AppPager.getPageInfo(ddlList, pageCount, list.size(), pageId);
//
//            Result.ok(pageInfo, InfoCode.SUCCESS, response);
//            return null;
//        } catch (Exception e) {
//            e.printStackTrace();
//            Result.ok(null, InfoCode.FAILURE, response);
//            return null;
//        }
//    }
//
//    @RequestMapping(value = "/addRemainCashDesc", method = RequestMethod.POST)
//    public String backSelectDriverList(RemainCashDesc r, HttpServletRequest request, HttpServletResponse response) {
//        logger.info("余额说明管理---添加---driver/addRemainCashDesc");
//        try {
//            List<RemainCashDesc> ddlList = rdm.selectRemainCashDesc(null);
//
//            if (ddlList != null && ddlList.size() > 0) {
//                RemainCashDesc rd = ddlList.get(0);
//                r.setId(rd.getId());
//                rdm.updateByPrimaryKey(r);
//                Result.ok(ddlList, InfoCode.SUCCESS, response);
//                return null;
//            } else {
//                rdm.insertSelective(r);
//                Result.ok(null, InfoCode.SUCCESS, response);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//
//    }
//
//    @RequestMapping(value = "/selectRemainCashDesc", method = RequestMethod.POST)
//    public String selectRemainCashDesc(RemainCashDesc r, HttpServletRequest request, HttpServletResponse response) {
//        logger.info("余额说明管理---查询---driver/selectRemainCashDesc");
//        try {
//            List<RemainCashDesc> ddlList = rdm.selectRemainCashDesc(null);
//            if (ddlList != null && ddlList.size() > 0) {
//                Result.ok(ddlList.get(0), InfoCode.SUCCESS, response);
//                return null;
//            } else {
//                Result.ok(null, InfoCode.SUCCESS, response);
//                return null;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//
//    }
//
//    @RequestMapping(value = "/sendLoginkByOrderCode", method = RequestMethod.POST)
//    public String loginkTest(String orderCode, HttpServletRequest request, HttpServletResponse response)
//            throws IOException {
//        Order o = new Order();
//        o.setOrderCode(orderCode);
//        List<Order> ol = orderService.selectOrder(o);
//        if (ol != null && ol.size() > 0) {
//            if (ol.get(0).getLoginkStatus() == 0) {
//                Driver d = new Driver();
//                if (ol.get(0).getDriverPhone() != null) {
//                    d.setDriverAccount(ol.get(0).getDriverPhone());
//                    List<Driver> dl = driverService.selectDriverInfo(d);
//                    if (dl != null && dl.size() > 0) {
//                        int result = loginkUtil.sendXml(ol.get(0), dl.get(0), Integer.parseInt(ModelConfig.status));
//                        if (result == 1) { // update order getLoginkStatus is 1
//                            Order oo = new Order();
//                            oo.setId(ol.get(0).getId());
//                            oo.setLoginkStatus(1);
//                            orderService.updateOrderById(oo);
//                        }
//                    }
//                }
//            }
//        }
//        return null;
//    }
//
//    @RequestMapping(value = "/sendLoginkByOrderCodeList", method = RequestMethod.POST)
//    public String sendLoginkByOrderCodeList(HttpServletRequest request, HttpServletResponse response)
//            throws IOException {
//        Order o = new Order();
//        o.setOrderStatus("15");
//        o.setLoginkStatus(0);
//        List<Order> ol = orderMapper.selectOrderForLogink(o);
//        if (ol != null && ol.size() > 0) {
//            int j = 0;
//            for (Order order : ol) {
//                if (order.getLoginkStatus() == 0) {
//                    Driver d = new Driver();
//                    if (order.getDriverPhone() != null) {
//                        d.setDriverAccount(order.getDriverPhone());
//                        List<Driver> dl = driverService.selectDriverInfo(d);
//                        if (dl != null && dl.size() > 0) {
//                            Driver driver = dl.get(0);
//                            if (driver.getRoadTransportCertificateNumber() != null
//                                    && driver.getRoadTransportCertificateNumber() != ""
//                                    && !"123456789".equals(driver.getRoadTransportCertificateNumber())) {
//                                int result = loginkUtil.sendXml(order, driver, Integer.parseInt(ModelConfig.status));
//                                if (result == 1) { // update order
//                                    // getLoginkStatus with 1
//                                    Order oo = new Order();
//                                    oo.setId(order.getId());
//                                    oo.setLoginkStatus(1);
//                                    orderService.updateOrderById(oo);
//                                    System.out.println("LOG-send success:" + j++);
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//
//        }
//        return null;
//    }

}
